﻿using FFmpeg.AutoGen;
using System;

namespace FFmpegLib
{
    public sealed unsafe class FSwsContext : IDisposable
    {
        private SwsContext* swsCtx;
        public SwsContext* Ctx { get => swsCtx; }

        public FSwsContext(FAVFrame frame, AVPixelFormat dstFmt, int width = 0, int height = 0)
        {
            swsCtx = FFmpegUtils.GetSwsContext(frame.Ptr, dstFmt, width, height);
        }

        public FSwsContext(SwsContext* ctx)
        {
            swsCtx = ctx;
        }

        public FAVFrame ConvertVideoFrameToYUV(FAVFrame src)
        {
            FAVFrame dst = new FAVFrame();
            dst.Width = src.Width;
            dst.Height = src.Height;
            int ret = ffmpeg.sws_scale(swsCtx, src.Ptr->data, src.Ptr->linesize, 0, src.Ptr->height, dst.Ptr->data, dst.Ptr->linesize);
            if (ret < 1)
            {
                string msg = FFmpegUtils.GetErrorMessage(ret);
                dst.Dispose();
            }
            return dst = null;
        }

        #region dispose
        private bool disposedValue;
        protected void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (swsCtx != null)
                        ffmpeg.sws_freeContext(swsCtx);
                    swsCtx = null;
                }
                disposedValue = true;
            }
        }

        public void Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}